/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";

import getProSizeDetail from '../mutation/ProSizeDetailMutation/getProSizeDetail'  //读取信息;
import saveProSizeDetail from "../mutation/ProSizeDetailMutation/saveProSizeDetail"  //保存信息


import GetQiNiuToken from "../mutation/GetQiNiuTokenMutation"  //上传图片获取token
import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片

import {Header,ViewImgList} from'../components/PackStep_Header';
import AddImgModal from "../components/AddImgModal";  //上传图片
import FileUpData from '../components/FileUpDataPro'  //上传附件

import {message,Modal} from 'antd';
import {Button} from 'fly';

import "../css/TechRequ.css";

import {_Button,_Input} from "ANT_DE";

import Config from "../../../../util/Config"
const Input = _Input;


/*
 * 工艺要求  展示层  ui纯UI无状态组件
 * */
/*导出组件*/
export default class ProcessDemand extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            imgList:[],
            fileList:[],

            token:"",
            text:"",

            previewVisible:false,  //图片预览
            previewImage: '',

            dis_btn:false,
            picRemoveList:[]
        };

        this.FixedImgSrc = Config.qiuniu;
        this.sizeDetailId = "";

        this.addImg = this.addImg.bind(this);
        this.addFileImg = this.addFileImg.bind(this);

        this.handleTextChange = this.handleTextChange.bind(this);
        this.save = this.save.bind(this);

        this.handleCancel = this.handleCancel.bind(this);

        this.addFileItem = this.addFileItem.bind(this);
        this.textCatch = this.textCatch.bind(this);
    }

    filterAttr(name,list,testAttr){
        for(let key in list){
            if(list[key][name] === testAttr){
                return false
            }else{
                return true
            }
        }
    }

    // 图片验证格式方法,返回false保存时调用 textCatch
    textTestReg(text){
        // 是否全部为空格
        const T  =  text,
            R = "^[ ]+$",
            RE = new RegExp(R);
        if( RE.test(T)){ return false }
    }


    //  图片格式错误
    textCatch(){
        message.info("请输入合法字符");
        this.setState({dis_btn:false})
    }

    //  验证格式需要通过obj传递到另一个组件调用，必须要在当前proto原型上，不可添加到自由属性.
    accept = ".jpg,.png,.gif,.jpeg,.bmp";
    fileAccept = ".pdf,.xlsx,.xls,.docx,.doc";

    save(){
        this.setState({dis_btn:true});

        const fileList = this.state.fileList,
            text = this.state.text;

        // 验证文本格式
        if(this.textTestReg(text) === false){
            this.textCatch();
            return
        }

        // 筛选文件当前是否为上传中状态
        for(let key in fileList){
            if(fileList[key].status === "uploading"){
                message.info("文件正在上传中");
                this.setState({dis_btn:false});
                return false
            }
        }

        Relay.Store.commitUpdate(new saveProSizeDetail({
                pdId:this.pdId,
                sizeDetailId:this.sizeDetailId,
                content:text,
                fileJSON:JSON.stringify(this.state.fileList),
                imgJSON:JSON.stringify(this.state.imgList)
            }),{
                onSuccess:(res)=>{
                    let data = res.saveProSizeDetail.responseData;
                    if(data.errorCode == 0){
                        setTimeout(()=>{
                            this.setState({
                                dis_btn:false
                            });
                            message.success("保存成功");
                        },500)
                    }else if(data.errorCode == 500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败")
                }
            }
        );

        let R = this.state.picRemoveList;
        if(R.length === 0 ){ return; }

        Relay.Store.commitUpdate(
                new DelQiniuFileMutation({
                    fileKey: R.join(",")
                }),
            {
                onFailure: () => {
                    message.error("网络请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        this.setState({picRemoveList:[]});
                    } else {message.error("上传图片失败，请重试")}
                }
            }
        )
    }

    componentWillMount() {
        this.pdId = this.props.pdId;

        // 获得上次保存的数据
        Relay.Store.commitUpdate(new getProSizeDetail({
                pdId:this.pdId
            }),{
                onSuccess:(res)=>{
                    let data = res.getProSizeDetail.responseData;
                    const con = data.proSizeDetailModel;

                    if(data.errorCode == 0){
                        let  com_file = con.fileJSON,
                            com_img = con.imgJSON,
                            content = con.content,
                            A = [],B=[];

                        (!com_img) ? A = [] : A = JSON.parse(com_img);
                        (!com_file) ? B = [] : B = JSON.parse(com_file);

                        this.setState({
                            imgList:A,
                            fileList:B,
                            text:content
                        });

                        //  主键ID
                        this.sizeDetailId = con.sizeDetailId;
                    }else if(data.errorCode == 500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败")
                }
            }
        );

        //获取上传图片所需的token
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        });
                    }else if(errorCode==500){
                        message.error("服务器错误，请联系管理员")
                    }
                },
                onFailure:()=>{
                    message.error("网络请求失败")
                }
            }
        );
    }

    addImg(){
        if( this.state.imgList.length >= 10 ){ message.info("最多可上传10张图片"); return; }
        this.refs.addFileImgModal.setState({
            visible:true
        })
    }

    handleTextChange(e){
        this.setState({
            text:e.target.value
        })
    }

    //上传图片配置
    uploadPlugin = {
        className:"packagSteps_updata",
        action:"http://up-z2.qiniu.com",
        beforeUpload:this.beforeImgUpload,
        listType:"picture-card",
        accept:this.accept,
    };

    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload,
        accept:this.fileAccept,
    };

    beforeImgUpload(file){
        const MaxSize = 8;  //最大限度 8M;
        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif" && file.type !== "image/bmp"){
            message.error("图片格式错误");
            return false;
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }
    }

    fileBeforeload(e){
        let Reg = [".xlsx",".xls", ".PDF", ".docx", ".doc"];  //格式
        function formatTest(reg,name){
            if(!reg || !name){ return; }
            const D = Array.from(reg),
                N = name.toLowerCase();
            for(let i in D){
                const I = D[i].toLowerCase();
                if(N.lastIndexOf(I) !== -1){
                    return true
                }
            }
            return false;
        }
        if(!!e.name){
            if(formatTest(Reg,e.name)) {
                return true
            }else{
                message.error("文件格式错误，请重新选择");
                return false;
            }
        }
    }

    //上传图片成功回调
    addFileImg({file,text}){
        if (file) {
            this.state.imgList.push({file,text});
            this.setState({
                imgList: this.state.imgList
            })
        }
    }

    // 预览图片
    handlePreview = (index) => {
        this.setState({
            previewVisible:true,
            previewImage:this.FixedImgSrc + this.state.imgList[index].file.response.key
        })
    };

    // 删除图片
    picRemove(index){
        //下列固定为0，因为list最多只能上传一个，固0
        const Rn =  this.state.imgList[index].file.response.key;
        //过渡动画
        this.state.imgList[index].file.__transClass = "leave";
        // 伪更新
        this.setState({ imgList:this.state.imgList });
        // 记录删除操作;
        this.state.picRemoveList.push(Rn);
        setTimeout(()=>{
            this.state.imgList.splice(index,1);
            this.setState({
                imgList:this.state.imgList
            })
        },300);
    }


    // 预览图片关闭
    handleCancel = ()=>{
        this.setState({
            previewVisible:false,
        })
        // 优化用户体验，延时一秒清空图片
        setTimeout(()=>{
            this.setState({
                previewImage:""
            })
        },700);
    }


    addFileItem(fileList){
        this.state.fileList = fileList;
        this.setState({
            fileList:this.state.fileList
        })
    }

    componentWillUnmount(){
        // console.log("unmount");
    }

    handleClickSelf(){
        message.warning("附件最多允许上传5个")
    }
    
    render(){
        const {text,token,imgList,previewVisible,previewImage,fileList,dis_btn} = this.state;

        return (
            <div className="poduction_manage_tab_box">
                <div className="poduction_techRequ">
                    <div className="poduction_techRequ_header-text">
                        <Input type="textarea"
                               className="poduction_techRequ_textInput"
                               value={text} maxlength="2000"
                               placeholder="请填写尺寸表"
                               onChange={this.handleTextChange}
                               maxLength="2000"
                        />
                    </div>
                    <div className="poduction_techRequ_hea-btn">
                        <div>

                            <Header
                                className="_left"
                                No1={this.addImg}
                            />

                            {/*上传文件*/}
                            <FileUpData
                                className="poduction_techRequ_updataFile"
                                filePlugin={this.fileUploadPlugin}
                                fileList={fileList}
                                callBack={this.addFileItem}   //回调，第一个参数为file,第二个参数为本地name
                                token={token}
                                isShowTrigger={fileList.length < 5}
                                handleClickSelf={this.handleClickSelf}
                            />
                        </div>


                        <div>
                            {
                                imgList.length !== 0 && imgList.map((item,index)=>
                                    <ViewImgList
                                        key={item.file.uid}
                                        imgSrc={`${this.FixedImgSrc + item.file.response.key}`}
                                        imgName={item.file.name}
                                        handlePreview={(e)=>this.handlePreview(index)}
                                        handleRemove={(e)=>this.picRemove(index)}
                                        textValue={item.text}
                                        transClass={item.file.__transClass}   //过渡动画类，中途插入
                                    />
                                )
                            }
                        </div>

                    </div>

                    <div className="packagSteps_footer">
                        <Button type="primary" onClick={this.save} loading={dis_btn} disabled={dis_btn}> 保存 </Button>
                    </div>

                    {/*添加上传图片*/}
                    <AddImgModal
                        uploadPlugin = {this.uploadPlugin}
                        ref="addFileImgModal"
                        token={token}   // 上传图片时，必须的token，(此token异步返回)
                        addFileImg={this.addFileImg}   //上传成功的回调，第一个参数的第一个属性为返回的fill,第二个属性为text描述
                        //  text 描述 props配置信息
                        TextProps={{  className:"packagSteps_AddImgModal_textArea",
                            rows:3,
                            placeholder:"请输入描述信息",
                        }}
                        limit={{width:500,height:500}} //最小宽高限制参数
                    />

                    {/*预览图片*/}
                    <Modal className="production_preview" visible={previewVisible} width={800} footer={null} onCancel={this.handleCancel}>
                        <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    </Modal>
                </div>

            </div>
        )
    }
}